<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title></title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- 引入 layui.css -->
  <link href="//unpkg.com/layui@2.11.2/dist/css/layui.css" rel="stylesheet">
  <script src="../jquery-3.7.1.min.js"></script>
  <style>
    /* * {
        margin: 0;
        padding: 0;
    }

    #form {
        width: 500px;
        height: 300px;
        border: 2px solid black;
        margin: auto;
        line-height: 42px;
        margin-top: 40px;
        border-radius: 4%;
    }

    #id_text {
        margin-top: 20px;
        margin-left: 590px;
    }

    #table {
        margin: auto;
        margin-top: 20px;
        width: 900px;
    }

    td {
        height: 50px;
    } */
    #form {
      width: 100%;
    }

    #table {
      border: 2px solid black;
      width: 100%;
      height: 30px;
    }

    thead tr {
      width: 800px;
      height: 80px;
    }

    .mg {
      margin-top: 10px;
    }

    button {
      width: 80px;
      height: 35px;
      background-color: #1e9fff;
      border: none;
      font-size: 16px;
      font-weight: 600;
      color: white;
    }
  
    
  </style>
</head>

<body>
  <div class="layui-layout layui-layout-admin">
    <div class="layui-header">
      <div class="layui-logo layui-hide-xs layui-bg-black">后台管理系统</div>
      <!-- 头部区域（可配合layui 已有的水平导航） -->
      <ul class="layui-nav layui-layout-left">
        <!-- 移动端显示 -->
        <li class="layui-nav-item layui-show-xs-inline-block layui-hide-sm" lay-header-event="menuLeft">
          <i class="layui-icon layui-icon-spread-left"></i>
        </li>
        <li class="layui-nav-item layui-hide-xs"><a href="javascript:;">nav 1</a></li>
        <li class="layui-nav-item layui-hide-xs"><a href="javascript:;">nav 2</a></li>
        <li class="layui-nav-item layui-hide-xs"><a href="javascript:;">nav 3</a></li>
        <li class="layui-nav-item">

        </li>
      </ul>
      <ul class="layui-nav layui-layout-right">
        <li class="layui-nav-item layui-hide layui-show-sm-inline-block">
          <a href="javascript:;">
            <img src="//unpkg.com/outeres@0.0.10/img/layui/icon-v2.png" class="layui-nav-img">
            tester
          </a>
          <dl class="layui-nav-child">
            <dd><a href="javascript:;">Your Profile</a></dd>
            <dd><a href="javascript:;">Settings</a></dd>
            <dd><a href="javascript:;">Sign out</a></dd>
          </dl>
        </li>
        <li class="layui-nav-item" lay-header-event="menuRight" lay-unselect>
          <a href="javascript:;">
            <i class="layui-icon layui-icon-more-vertical"></i>
          </a>
        </li>
      </ul>
    </div>
    <div class="layui-side layui-bg-black">
      <div class="layui-side-scroll">
        <!-- 左侧导航区域（可配合layui已有的垂直导航） -->
        <ul class="layui-nav layui-nav-tree" lay-filter="test">
          <li class="layui-nav-item"><a href="./商品管理.html">商品管理</a></li>
          <!-- <li class="layui-nav-item"><a href="../图表/第三题图表.html">数据表</a></li> -->
          <!-- <li class="layui-nav-item"><a href="./个人中心.html">个人中心</a></li> -->
          
          <li class="layui-nav-item" lay-header-event="menuRight" lay-unselect>
            <a href="./登录.html">
              <i class="layui-icon layui-icon-return"></i>退出
            </a>
          </li>
        </ul>
      </div>
    </div>
    <!-- 首页列表 -->
    <div class="layui-body">
      
      <blockquote class="layui-elem-quote layui-text">
        <span class="layui-breadcrumb" lay-separator=">">
          <a href="">
            <i class="layui-icon layui-icon-spread-left"></i>&emsp;首页</a>
          <a href="">商品列表</a>
        </span>
      </blockquote>
      <!-- 表单 -->
      <form action="" id="form" style="text-align: center;">
        <input type="hidden" name="id" value="">
        商品名称： <input type="text" name="goods_name" />
        &emsp;&emsp; 库存： <input type="text" name="stock" />
        &emsp;&emsp; 价格： <input type="text" name="price" />
        是否上架： <input type="text" name="status" />
        &emsp;&emsp; 已售： <input type="text" name="sold" />
        &emsp;&emsp; 图片： <input type="text" name="img" class="mg" />
        <input type="hidden" name="created_at" value="">
        <input type="hidden" name="updated_at" value="">
        <input type="submit" value="提交" name="submit" />
      </form>
      <form action="" id="sel_form">
        &emsp; &emsp; &emsp;&emsp;&emsp;&emsp;&emsp;&emsp;
        <input type="text" id="id_text" placeholder="请输入ID">
        <button id="cha">查询</button>
      </form>
      <!-- 表格 -->
      <table border="2px" id="table"
        style="width: 1300px;height: 30px; text-align: center; margin: auto;margin-top: 50px;">
        <thead class="dd">
          <tr>
            <th>ID</th>
            <th>图片</th>
            <th>商品名称</th>
            <th>库存</th>
            <th>价格</th>
            <th>是否上架</th>
            <th>已售</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
      <div class="layui-card-body">

        <table class="layui-hide" lay-filter="test" id="ID-table-demo-data">
          <thead></thead>
          <tbody></tbody>
        </table>
      </div>
    </div>
    <br><br>
  </div>
  </div>
  </div>
  <br><br>
  </div>
  </div>
    <!-- 底部固定区域 -->
    底部固定区域
  </div>
  </div>
  <!-- 引入 layui.js -->
  <script src="//unpkg.com/layui@2.11.2/dist/layui.js"></script>
  <script>
    //JS 
    layui.use(['element', 'layer', 'util'], function () {
      var element = layui.element;
      var layer = layui.layer;
      var util = layui.util;
      var $ = layui.$;
      //头部事件
      util.event('lay-header-event', {
        menuLeft: function (othis) { // 左侧菜单事件
          layer.msg('展开左侧菜单的操作', { icon: 0 });
        },
        menuRight: function () {  // 右侧菜单事件
          layer.open({
            type: 1,
            title: '更多',
            content: '<div style="padding: 15px;">处理右侧面板的操作</div>',
            area: ['260px', '100%'],
            offset: 'rt', // 右上角
            anim: 'slideLeft', // 从右侧抽屉滑出
            shadeClose: true,
            scrollbar: false
          });
        }
      });
    });
    // 获取元素
    let tbody = document.querySelector("tbody")
    // 表单
    let form = document.querySelector("form")
    // 查询
    let cha = document.getElementById("cha")
    // 表单控件
    let g_id = document.querySelector("input[name = 'id']");
    let g_name = document.querySelector("input[name = 'goods_name']");
    let g_stock = document.querySelector("input[name = 'stock']");
    let g_price = document.querySelector("input[name = 'price']");
    let g_status = document.querySelector("input[name = 'status']");
    let g_sold = document.querySelector("input[name = 'sold']");
    let g_img = document.querySelector("input[name = 'img']");
    // 提交标签
    let btn = document.querySelector("input[name = 'submit']");
    // 页面加载完成
    window.onload = function () {
      getList();
      form.addEventListener("submit", subFun);
      tbody.addEventListener("click", tbodyFun);
    }
    // 渲染数据
    function romance(arr) {
      let text = "";
      arr.forEach(item => {
        text += `
            <tr>
                <td>${item.id}</td>
                 <td>
                    <img src="${item.img}" alt="" width="100px">
                </td>
                <td>${item.goods_name}</td>
                <td>${item.stock}</td>
                <td>${item.price}</td>
                <td>${item.status == 1 ? '已上架' : '未上架'}</td>
                <td>${item.sold}</td>
                <td>                                    
                    <button data-id="${item.id}" class="delete-btn">删除</button>
                    <button data-id="${item.id}" class="edit-btn">修改</button>
                    <button onclick ='details(${item.id})'>查看详情</button>
                </td>
            </tr>
        `;
      });
      tbody.innerHTML = text;
    }
    // 获取列表数据
    function getList() {
      let xhr = new XMLHttpRequest();
      xhr.open("get", "https://liu.zzgoodqc.cn/goodsx/goodslist");
      xhr.send();
      xhr.responseType = "json";
      xhr.onload = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
          // console.log(xhr.response);
          romance(xhr.response.data)
        }
      }
    }
    // 修改提交事件处理函数
    function subFun(e) {
      e.preventDefault();
      let formData = new FormData(form);
      // 检查必填字段
      if (!g_name.value || !g_stock.value || !g_price.value) {
        alert('请填写完整信息');
        return;
      }
      if (btn.value === "提交") {
        addList("https://liu.zzgoodqc.cn/goodsx/add", formData);
      } else {
        updataList("https://liu.zzgoodqc.cn/goodsx/update", formData);
        btn.value = "提交";
      }
      // 重置表单
      form.reset();
      g_id.value = ''; // 清空隐藏的id字段
    }
    // 添加成功后重置表单
    function addList(url, data) {
      let xhr = new XMLHttpRequest();
      xhr.open("post", url);
      xhr.send(data);
      xhr.responseType = "json"
      xhr.onload = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
          console.log(xhr.response);
          getList();
          form.reset();
        }
      }
    }

    // 添加修改数据函数
    function updataList(url, data) {
      let xhr = new XMLHttpRequest();
      xhr.open("post", url);
      xhr.send(data);
      xhr.responseType = "json"
      xhr.onload = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
          console.log(xhr.response);
          getList();
        }
      }
    }
    // 添加
    function getObjData(id) {
      let xhr = new XMLHttpRequest();
      xhr.open("get", `https://liu.zzgoodqc.cn/goodsx/getone?id=${id}`);
      xhr.send();
      xhr.responseType = "json";
      xhr.onload = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
          let data = xhr.response.data;
          g_id.value = data.id;
          g_name.value = data.goods_name;
          g_stock.value = data.stock;
          g_price.value = data.price;
          g_status.value = data.status;
          g_sold.value = data.sold;
          g_img.value = data.img;
        }
      }
    }
    // 事件委托
    function tbodyFun() {
      if (event.target.innerText === "删除") {
        let i = event.target.dataset.id;
        delFun(i);
      }
      if (event.target.innerText === "修改") {
        let i = event.target.dataset.id;
        getObjData(i)
        btn.value = "修改";
      }
    }
    // 删除
    function delFun(g_id) {
      let xhr = new XMLHttpRequest();
      xhr.open("get", `https://liu.zzgoodqc.cn/goodsx/delete?id=${g_id}`);
      xhr.send();
      xhr.onload = function () {
        if (xhr.status == 200 && xhr.readyState == 4) {
          // console.log(xhr.response);
          getList();
        }
      }
    }

    // 查询
    // cha.onclick = function () {
    //     event.preventDefault();
    //     chat(new FormData(this));
    // }

    function chat(data) {
      let xhr = new XMLHttpRequest();
      xhr.open("post", "https://liu.zzgoodqc.cn/goodsx/search")
      xhr.send(data);
      xhr.onload = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
          romance(JSON.parse(xhr.response).data)
        }
      }
    }
    // 根据id获取商品详情
    function getObjData(gid) {
      let xhr = new XMLHttpRequest();
      xhr.open("get", `https://liu.zzgoodqc.cn/goodsx/detail?id=${gid}`);
      xhr.send();
      xhr.responseType = "json";
      xhr.onload = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
          g_id.value = xhr.response.data.id;
          g_name.value = xhr.response.data.goods_name;
          g_price.value = xhr.response.data.price;
          g_sold.value = xhr.response.data.sold;
          g_status.value = xhr.response.data.status;
          g_stock.value = xhr.response.data.stock;
          g_img.value = xhr.response.data.img;
        }
      }
    }
    // 修改
    function updataList(url, data) {
      let xhr = new XMLHttpRequest();
      xhr.open("post", url);
      xhr.send(data);
      xhr.responseType = "json"
      xhr.onload = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
          getList();
        }
      }
    }
    // 查看详情
    function details(id) {
      // 阻止默认事件
      event.preventDefault();
      // 发送请求获取详情数据
      let xhr = new XMLHttpRequest();
      xhr.open("get", `https://liu.zzgoodqc.cn/goodsx/detail?id=${id}`);
      xhr.send();
      xhr.responseType = "json";
      xhr.onload = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
          let data = xhr.response.data;
          // 使用LayUI的弹层组件显示详情
          layui.use('layer', function () {
            var layer = layui.layer;
            let content = `
                    <div style="padding: 20px;">
                        <div><strong>ID:</strong> ${data.id}</div>
                        <div><strong>商品名称:</strong> ${data.goods_name}</div>
                        <div><strong>图片:</strong> <img src="${data.img}" style="max-width: 200px; max-height: 200px;"></div>
                        <div><strong>库存:</strong> ${data.stock}</div>
                        <div><strong>价格:</strong> ${data.price}</div>
                        <div><strong>状态:</strong> ${data.status == 1 ? '已上架' : '未上架'}</div>
                        <div><strong>已售:</strong> ${data.sold}</div>
                        <div><strong>创建时间:</strong> ${data.created_at}</div>
                        <div><strong>更新时间:</strong> ${data.updated_at}</div>
                    </div>
                `;
            // 弹出详情窗口
            layer.open({
              type: 1,
              title: '商品详情',
              area: ['500px', 'auto'],
              content: content
            });
          });
        }
      };
    }

  </script>
</body>

</html>